import { world } from "@minecraft/server";
import { Dimensions } from "@sapi-game/constants";
import { AutoStopComponent } from "@sapi-game/gameComponent/common/autoStop";
import { PlayerGroupSet } from "@sapi-game/gamePlayer/groupSet";
import { Game } from "@sapi-game/main";
import { MonopolyItems } from "../components/items";
import { monopolyModule } from "../moudle";
import { MonopolyPlayer } from "../player";

export class MonopolyMainState extends monopolyModule.State {
    readonly startPos = { x: -179, y: -43, z: 144 };

    override onEnter(): void {
        this.addComponent(MonopolyItems);
        Dimensions.Overworld.setBlockType(this.startPos, "minecraft:air");
        this.runner.run(async (r) => {
            await r.wait(1);
            r.do(() =>
                Dimensions.Overworld.setBlockType(
                    this.startPos,
                    "minecraft:redstone_block"
                )
            );
            await r.wait(10);
            r.do(() => this.listenForEnd());
            r.do(() => this.listenForPlayers());
        });
    }

    listenForEnd() {
        const players = world.getPlayers({
            scoreOptions: [{ objective: "dfw_team", minScore: 1 }],
        });
        const group = this.playerManager.groupBuilder.fromPlayers(players);
        //自动释放
        this.addComponent(AutoStopComponent<MonopolyPlayer>, {
            groupSet: new PlayerGroupSet([group]),
            onStopGame: () => {
                this.engine.stopGame();
            },
            onLeave: (p) => {
                group.sendMessage(p.name + " 离开了大富翁游戏");
            },
            immediateDie: true,
        });
        this.subscribe(Game.events.interval, () => {
            if (
                Dimensions.Overworld.getBlock(this.startPos)?.typeId ==
                "minecraft:air"
            ) {
                this.engine.stopGame();
            }
        });
    }

    listenForPlayers() {
        this.addComponent(AutoStopComponent, {
            groupSet: new PlayerGroupSet([
                this.playerManager.groupBuilder.fromPlayers(this.getPlayers()),
            ]),
            onStopGame: () => {
                this.engine.stopGame();
            },
            onLeave: (p) => {
                if (p.player) {
                    world.scoreboard
                        .getObjective("dfw_team")
                        ?.removeParticipant(p.player);
                }
                this.getPlayers().forEach((p) =>
                    p.sendMessage(
                        "§l§c[!]> §r§7玩家 §e" + p.name + " §7已离开大富翁游戏"
                    )
                );
            },
            immediateDie: true,
        });
    }

    getPlayers() {
        try {
            return world
                .getPlayers({
                    scoreOptions: [{ objective: "dfw_team", minScore: 1 }],
                })
                .filter((p) => p != undefined);
        } catch {
            return [];
        }
    }
}
